package source;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;



public class PartecipanteDataAccess {

	Connection connection;


	public PartecipanteDataAccess() {

		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost/poliholdem";
			connection = DriverManager.getConnection(url, "phm", "phm");      
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 
	 * @param id_pl
	 * @param id_t
	 * @param posiz_t
	 * @param punti_t
	 * @param guad_t
	 * @return
	 * @throws SQLException
	 */
	public boolean insertNewPartecipante(int id_pl, int id_t, int posiz_t, double punti_t, double guad_t) throws SQLException{

		PreparedStatement stm = connection.prepareStatement("INSERT INTO partecipante_torneo"+
		" VALUES(?, ?, ?, ?, ?)");

		stm.setInt(1,id_pl);
		stm.setInt(2,id_t);
		stm.setInt(3,posiz_t);
		stm.setDouble(4,punti_t);
		stm.setDouble(5,guad_t);

		return !stm.execute();
	}
	
	
	/**
	 * 
	 * @param player
	 * @return
	 * @throws SQLException
	 */
	public ArrayList<Partecipante> getHistoryPlayer(Player player) throws SQLException{
		
		
		ArrayList<Partecipante> result = new ArrayList<Partecipante>();
		
		PreparedStatement stm = connection.prepareStatement("SELECT * FROM partecipante_torneo"+
		" WHERE id_player=?");
		stm.setInt(1, player.getId_player());
		ResultSet rs = stm.executeQuery();
		
		while (rs.next()) {
			Partecipante part = new Partecipante(rs.getInt("id_player"), rs.getInt("id_torneo"), 
					rs.getInt("posizione"),rs.getDouble("punti_torneo"),
					rs.getDouble("guadagni_torneo"));
			result.add(part);
		}
		
		if(result.isEmpty()){

			System.out.println("No partecipanti found with id="+player.getId_player());
			return null;
		}

		return result;
	}


	/**
	 * 
	 * @param idT
	 * @return
	 * @throws SQLException
	 */
	public boolean deleteAllPartecipantiTorneo(int idT) throws SQLException {
		
		PreparedStatement stm = connection.prepareStatement("DELETE FROM poliholdem.partecipante_torneo " +
			"WHERE id_torneo = ?");	
		stm.setInt(1, idT);	

		return !stm.execute();
		
	}
	
}